package com.lazydong.apiforward.gateway;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.io.File;
import java.util.List;
import java.util.ServiceLoader;

@SpringBootApplication
public class ApiForwardGatewayApplication implements CommandLineRunner {

    @Autowired(required = false)
    List<StartupCompleted> startupCompleted;

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(ApiForwardGatewayApplication.class);
        ServiceLoader<PidFilePath> pidFilePaths = ServiceLoader.load(PidFilePath.class);
        long count = pidFilePaths.stream().count();
        if (count > 1) {
            throw new RuntimeException("More than one pidFilePath was found");
        }
        for (PidFilePath pidFilePath : pidFilePaths) {
            File file = new File(pidFilePath.getPidFilePath());
            ApplicationPidFileWriter pidFileWriter = new ApplicationPidFileWriter(file);
            springApplication.addListeners(pidFileWriter);
        }
        springApplication.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        ServiceLoader<StartupCompleted> startupCompleteds = ServiceLoader.load(StartupCompleted.class);
        startupCompleteds.forEach(StartupCompleted::onStartupCompleted);
        if (startupCompleted != null) {
            startupCompleted.forEach(StartupCompleted::onStartupCompleted);
        }
    }
}